﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class ListNode
{
    public int val;
    public ListNode next;
    public ListNode(int val = 0, ListNode next = null)
    {
        this.val = val;
        this.next = next;
    }
}
namespace Algorithm.Middle_2_AddTwoNumbers
{
    class MainProject
    {
        static void Main(string[] args)
        {
            ListNode node1 = new ListNode(2, new ListNode(4, new ListNode(9)));
            ListNode node2 = new ListNode(5, new ListNode(6, new ListNode(4, new ListNode(9))));
            AddTwoNumbers(node1, node2);
            Console.ReadKey();
        }
        public static ListNode AddTwoNumbers(ListNode l1, ListNode l2)
        {
            ListNode tempNode1 = l1;
            ListNode tempNode2 = l2;

            ListNode root = new ListNode();
            ListNode tempRoot = root;

            int carry = 0;
            int sum = 0;
            while (tempNode1 != null || tempNode2 != null || carry != 0)
            {
                sum = 0;
                sum += carry;
                if (tempNode1 != null) sum += tempNode1.val;
                if (tempNode2 != null) sum += tempNode2.val;
                int bit = sum % 10;
                int otherBit = sum / 10;
                tempRoot.val = bit;
                carry = otherBit;
                tempNode1 = tempNode1?.next;
                tempNode2 = tempNode2?.next;
                if (tempNode1 != null || tempNode2 != null || carry!=0) { tempRoot.next = new ListNode(); tempRoot = tempRoot.next;  }
            }

            return root;
        }
    }
}
